package com.efounder.fragment;


import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.core.xml.StubObject;
import com.efounder.chat.activity.SetWorkGroupActivity;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.model.Group;
import com.efounder.chat.struct.MessageChildTypeConstant;
import com.efounder.chat.utils.GroupNameUtil;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.message.manager.JFMessageManager;
import com.efounder.message.struct.IMStruct002;

import com.efounder.mobilecomps.contacts.User;
import com.efounder.ospmobilelib.R;
import com.pansoft.resmanager.ResFileManager;

import net.sf.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

/**
 * A simple {@link Fragment} subclass.
 */
@SuppressLint("ValidFragment")
public class WorkLogFragment extends BaseFragment {

    private String mWorklogStr;
    private int mGroupId;
    private String userId;
    private StubObject mStubObject;
    private View mView;
    private LinearLayout llWritelog;
    private TextView tvWriteWorklog;
    private EditText etWriteWorklog;

    //标题栏
    private View viewTitle;
    private TextView tvTitle;
    private String mMenuIconStr;
    private ImageView ivMenuIcon;

    @SuppressLint("ValidFragment")
    public WorkLogFragment(StubObject object) {
        this.mStubObject = object;
    }

    public WorkLogFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        mView = inflater.inflate(R.layout.fragment_work_log, container, false);
        llWritelog = (LinearLayout) mView.findViewById(R.id.ll_write_log);
        tvWriteWorklog = (TextView) mView.findViewById(R.id.tv_write_worklog);
        etWriteWorklog = (EditText) mView.findViewById(R.id.et_write_worklog);
        viewTitle = mView.findViewById(R.id.view_yewu_title);
        tvTitle = (TextView) mView.findViewById(R.id.tv_yewu_frag_name);
        ivMenuIcon = (ImageView) mView.findViewById(R.id.iv_yewu_frag_icon);
        return mView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        userId = EnvironmentVariable.getUserID();
        if (mStubObject != null) {
            Hashtable stubTable = mStubObject.getStubTable();
//            mGroupId = Integer.valueOf((String) stubTable.get("groupId"));
            if (stubTable.containsKey("caption")) {
                tvTitle.setText((String) stubTable.get("caption"));
            } else {
                viewTitle.setVisibility(View.GONE);
            }
            if (stubTable.containsKey("menuIcon")) {
                mMenuIconStr = "file://" + ResFileManager.IMAGE_DIR + "/" + (String) stubTable.get("menuIcon");
                LXGlideImageLoader.getInstance().displayImage(getContext(), ivMenuIcon, mMenuIconStr, R.drawable.iframe_icon_refresh, R.drawable.iframe_icon_refresh);
            } else {
                viewTitle.setVisibility(View.GONE);

            }
        }

        llWritelog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mWorklogStr = String.valueOf(etWriteWorklog.getText());
                if(etWriteWorklog.getText().toString().trim().length()==0){
                    showToast("你还未填写任何内容");
                }else{
                    if (EnvironmentVariable.getProperty(userId + "workgroup") == null
                            || "".equals(EnvironmentVariable.getProperty(userId + "workgroup"))) {
                        new android.app.AlertDialog.Builder(getActivity())
                                .setMessage("您还未设置工作群,请前往设置")
                                .setNegativeButton(R.string.common_text_cancel, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                    }
                                })
                                .setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        getActivity().startActivity(new Intent(getActivity(), SetWorkGroupActivity.class));
                                    }
                                }).show();
                    }else {
                        mGroupId = Integer.parseInt(EnvironmentVariable.getProperty(userId + "workgroup"));
                        sendWorklog(mGroupId, mWorklogStr);
                        etWriteWorklog.setText("");
                    }

                }
            }
        });

    }

    /**
     * 发送工作日志消息
     * @param groupId
     * @param workStr
     */
    private void sendWorklog(int groupId, String workStr) {

        Group group = WeChatDBManager.getInstance().getGroupWithUsers(groupId);
        User user = GroupNameUtil.getGroupUser(group.getGroupId(),
                Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)));
        String userName = GroupNameUtil.getGroupUserName(user);

        String title = userName + "的日志";
        String systemName = "工作日志";
        Long currentTime = new Date().getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(currentTime);
        String d = format.format(date);
        String finalTime = Integer.valueOf(d.substring(5, 7)) + "月" +
                Integer.valueOf(d.substring(8, 10)) + "日" +
                d.substring(11, 16) + "分";
        String fromUserId = EnvironmentVariable.getUserID();

        Map<String, Object> map = new HashMap<>();
        String imgUrl = "http://panserver.solarsource.cn:9692/panserver/files/7e58f86f-646e-4206-84bc-3c6d6d62a052/download";
        map.put("title", title);
        map.put("image", imgUrl);
        map.put("smallIcon", imgUrl);
        map.put("time", finalTime);
        map.put("content", workStr);
        map.put("systemName", systemName);
        map.put("AndroidShow", "com.efounder.chat.fragment.DailyDetailFragment");
        map.put("show", "ShowRNViewController");
        map.put("viewType", "display");
        JSONObject jsonObject1 = JSONObject.fromObject(map);
        IMStruct002 imStruct002 = new IMStruct002();
        try {
            imStruct002.setBody(jsonObject1.toString().getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        imStruct002.setTime(Long.valueOf(currentTime));
        imStruct002.setToUserType((byte) 1);
        imStruct002.setToUserId(groupId);
        imStruct002.setFromUserId(Integer.valueOf(fromUserId));
        imStruct002.setMessageChildType(MessageChildTypeConstant.subtype_common);
        JFMessageManager.getInstance().sendMessage(imStruct002);
        showToast("发送成功");
    }

    private void showToast(String msg) {
        Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
    }
}
